from django.db import models

from system.models import Module, Language
from user.models import Student, Group, User


class Task(models.Model):
    """任务表（核心模型）"""

    title = models.CharField(max_length=200, db_comment="任务标题")
    language = models.ForeignKey(Language, on_delete=models.CASCADE)
    description = models.TextField(db_comment="任务描述")
    module = models.ForeignKey(Module, on_delete=models.CASCADE, related_name="tasks", db_comment="所属模块")
    difficulty = models.CharField(
        max_length=20,
        choices=[("easy", "简单"), ("medium", "中等"), ("hard", "困难")],
        default="medium",
        db_comment="难度等级"
    )
    deadline = models.DateTimeField(db_comment="截止时间")
    creator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="created_tasks",
                                db_comment="创建者")
    created_time = models.DateTimeField(auto_now_add=True, db_comment="创建时间")
    class Meta:
        db_table = "tb_task"
        verbose_name = "任务"
        verbose_name_plural = "任务"
        ordering = ["-created_time"]


class TaskAssignment(models.Model):
    """任务分配表（学生-任务关联）"""

    class AssignmentStatus(models.TextChoices):
        NOT_STARTED = "not_started", "未开始"
        IN_PROGRESS = "in_progress", "进行中"
        SUBMITTED = "submitted", "已提交"
        REVIEWED = "reviewed", "已审核"
        COMPLETED = "completed", "已完成"

    task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name="assignments", db_comment="关联任务")
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="assigned_tasks", db_comment="关联学生")
    group = models.ForeignKey(Group, on_delete=models.SET_NULL, null=True, blank=True, related_name="group_tasks",
                              db_comment="所属分组（可选）")
    status = models.CharField(
        max_length=20,
        choices=AssignmentStatus.choices,
        default=AssignmentStatus.NOT_STARTED,
        db_comment="任务状态（学生视角）"
    )
    submit_content = models.TextField(blank=True, null=True, db_comment="提交内容")
    submit_time = models.DateTimeField(null=True, blank=True, db_comment="提交时间")
    score = models.DecimalField(max_digits=5, decimal_places=1, null=True, blank=True, db_comment="评分")
    created_time = models.DateTimeField(auto_now_add=True, db_comment="分配时间")
    updated_time = models.DateTimeField(auto_now=True, db_comment="更新时间")

    class Meta:
        db_table = "tb_task_assignment"
        verbose_name = "任务分配"
        verbose_name_plural = "任务分配"
        unique_together = ("task", "student")  # 一个学生对一个任务只分配一次
